package com.example.untils;

import com.baomidou.mybatisplus.core.toolkit.AES;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.spec.SecretKeySpec;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

public class AESUtil {

    private static final String SECRET_KEY = "HZSECRET_KEY123+*/-546841QWERASD";

    private static final String SECRET = "d1104d7c3b616f0b";

    public static void main(String[] args) {
        String password = "123456";
        System.out.println(AES.encrypt(password, SECRET));
    }

    /**
     * 将字节流进行解密
     * @param filePath 文件路径
     * @return
     */
    public static byte[] decrypt(String filePath) throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        // 读取文件内容
        byte[] encryptedBytes = Files.readAllBytes(Paths.get(filePath));
//        zhi = encryptedBytes.length;
        // 创建 AES 解密器
        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
        cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);

        // 解密文件内容
        return cipher.doFinal(encryptedBytes);
        // 在这里编写解密逻辑，根据文件路径(filePath)进行解密操作
        // 返回解密后的文件内容，类型为字节数组(byte[])
    }

    /**
     * 将原文件进行加密
     * @param filePath 文件路径
     */
    public static void encryptFile(String filePath) throws IOException, NoSuchAlgorithmException,
            NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
        // 读取文件内容
        FileInputStream fis = new FileInputStream(filePath);
        byte[] fileBytes = new byte[(int) new File(filePath).length()];
        fis.read(fileBytes);
        fis.close();

        // 创建 AES 加密器
        Cipher cipher = Cipher.getInstance("AES");
        SecretKeySpec secretKeySpec = new SecretKeySpec(SECRET_KEY.getBytes(), "AES");
        cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);

        // 加密文件内容
        byte[] encryptedBytes = cipher.doFinal(fileBytes);

        // 将加密后的内容写回文件
        FileOutputStream fos = new FileOutputStream(filePath);
        fos.write(encryptedBytes);
        fos.close();
    }

}
